package com.micro.fast.upms.service.impl;

import com.micro.fast.common.exception.SystemException;
import com.micro.fast.common.response.ServerResponse;
import com.micro.fast.upms.dao.UpmsUserMapper;
import com.micro.fast.common.exception.UserException;
import com.micro.fast.upms.pojo.UpmsUser;
import com.micro.fast.upms.service.UpmsUserService;
import com.micro.fast.util.ExceptionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.micro.fast.common.response.BaseConst.*;

/**
 * @author lsy
 */
@Service(value = "upmsUserServiceImpl")
public class UpmsUserServiceImpl implements UpmsUserService {


  @Autowired
  private UpmsUserMapper upmsUserMapper;

  @Override
  public ServerResponse<UpmsUser> register(UpmsUser upmsUser, String repeatPassword){
    ServerResponse checkUsername = checkUsername(upmsUser.getUsername());
    ServerResponse checkEmail = checkEmail(upmsUser.getEmail());
    //校验两次输入密码是否一致
    if (upmsUser.getPassword().equals(repeatPassword)){
      throw new UserException(ExceptionUtil.contactCodeMsg(
          UserResponse.TWO_PASSWORD_NOT_SAME.getCode(),
          UserResponse.TWO_PASSWORD_NOT_SAME.getMsg()
      ));
    }
    //校验用户名,邮箱是否存在
    boolean success = checkUsername.isSuccess();
    boolean success1 = checkEmail.isSuccess();
    if (!success){
      throw new UserException(ExceptionUtil.contactCodeMsg(
         UserResponse.USERNAME_IS_HAVE.getCode()
          ,UserResponse.USERNAME_IS_HAVE.getMsg()));
    }
    if (!success1){
      throw new UserException(ExceptionUtil.contactCodeMsg(
          UserResponse.EMAIL_IS_HAVE.getCode()
          ,UserResponse.EMAIL_IS_HAVE.getMsg()));
    }
    upmsUser.setCtime(Long.valueOf(System.currentTimeMillis()));
    //todo 对密码进行加密处理

    int i = upmsUserMapper.insertSelective(upmsUser);
    //是否插入成功
    if (i<1){
      throw new SystemException(ExceptionUtil.contactCodeMsg(
          SystemResponse.DATABASE_INSERT_FAILURE.getCode()
          ,SystemResponse.DATABASE_INSERT_FAILURE.getMsg()));
    }
    return ServerResponse.successData(upmsUser);
  }

  @Override
  public ServerResponse checkUsername(String username) {
    int i = upmsUserMapper.countUsername(username);
    if (i>0){
      //用户名被占用
      return ServerResponse.error();
    }else{
      //用户名没被占用
      return ServerResponse.success();
    }
  }

  @Override
  public ServerResponse checkEmail(String email) {
    int i = upmsUserMapper.countEmail(email);
    if (i>0){
      //邮箱已被占用
      return ServerResponse.error();
    }else{
      //邮箱没被占用
      return ServerResponse.success();
    }
  }
  
}
